package com.waimai.filter;

import com.alibaba.fastjson.JSON;
import com.sun.net.httpserver.HttpsServer;
import com.waimai.common.BaseContext;
import com.waimai.common.R;
import com.waimai.domain.Employee;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//这个注解设置过滤器名字和拦截路径
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //设置放行的路径
        String requestURI = request.getRequestURI();
        // 把放行的路径写在数组里
        String[] Uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg/",
                "/user/login",
                "backend/page/demo/**"
        };
        //判断请求是否处理
        boolean check = check(Uris, requestURI);
        //判断是否拦截
        if (check) {
            System.out.println("拦截成功");
            filterChain.doFilter(request, response);
            return;
        }
        //判断是否登录
        if (request.getSession().getAttribute("employee") != null) {
            System.out.println("未登录");

            filterChain.doFilter(request, response);
            return;
        }
////        劝退代码
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;


}
    //比较老旧的技术判断路径是否存在数组中
    boolean check (String[] Uris,String requestURI){
        for (String url : Uris) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }

        }
        return false;}
}